import datetime
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import csv
import pathlib

def exist_file(name):#查找需要的文件是否存在
    path = pathlib.Path(name)
    if path.exists():
        return True
    else:
        return False

def read_account():#读取账号密码
    username = []
    password = []
    with open("account.csv", "r", newline="") as f:
        dataframe = csv.reader(f)
        next(dataframe)
        for i in dataframe:
            username.append(i[0])
            password.append(i[1])
    return username,password

def record(account,time):#记录
    with open("datatime.csv","a",encoding="utf-8",newline="") as f:
        writer = csv.writer(f)
        writer.writerow([account,time])

def signin(username,password):#实现自动登录并签到
    driver = webdriver.Edge()
    driver.get('https://my.4399.com/')
    driver.implicitly_wait(10)
    driver.find_element(By.CSS_SELECTOR, '.loginbtn').click()  # 点击
    time.sleep(1)
    login_frame = driver.find_element(By.CSS_SELECTOR, '#popup_login_frame')
    driver.switch_to.frame(login_frame)
    driver.find_element(By.CSS_SELECTOR, '#username').send_keys(username)  # 输入账号，密码
    time.sleep(1)
    driver.find_element(By.CSS_SELECTOR, '#j-password').send_keys(password)
    time.sleep(1)
    driver.find_element(By.CSS_SELECTOR, '.ptlogin_btn').click()
    time.sleep(3)
    driver.find_element(By.CSS_SELECTOR, '#j-btn-sign').click()
    time.sleep(1)

    driver.quit()


if not exist_file('account.csv'):#创建账户存储介质
    with open('account.csv','a',newline='') as f:
        writer = csv.writer(f)
        writer.writerow(['username','password'])
if not exist_file('datatime.csv'):
    with open('datatime.csv','a',newline='') as f:
        writer = csv.writer(f)
        writer.writerow(['account','time'])
if len(open('account.csv').readlines()) == 1:#存储首个账户
    username = input('请输入首行账号：')
    password = input('请输入首行密码：')
    with open("account.csv",'a',newline="") as f:
        writer = csv.writer(f)
        writer.writerow([username,password])
if exist_file('account.csv') and exist_file('datatime.csv'):
    username, password = read_account()
    count = len(username)
    for i in range(0, count):
        signin(username[i], password[i])
        t = datetime.datetime.now()
        record(username[i], t)